package cn.easyutil.util.platform.alibaba.alipay;

import java.util.HashMap;
import java.util.Map;

import cn.easyutil.util.javaUtil.JsonUtil;
import cn.easyutil.util.javaUtil.StringUtil;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * 阿里短信工具类
 * @author spc
 *
 */
public class AliSmsUtil {

	// 产品名称:云通信短信API产品,开发者无需替换
	private static final String product = "Dysmsapi";
	// 产品域名,开发者无需替换
	private static final String domain = "dysmsapi.aliyuncs.com";

	private String accessKeyId = "LTAIZGFK7enA1Ifb";
	private String accessKeySecret = "1IH81t9gaH4gtKdRQX3gCAvPxiVN6C";
	// 地区
	private  String area = "cn-hangzhou";
	// 过期时间
	private  String overTime = "10000";
	// 短信模板
	private String templateCode = "SMS_122298979";
	// 模板参数
	private Map<String, String> params = new HashMap<String, String>();
	// 短信签名
	private String signName = "沙沙野";

	public AliSmsUtil(){}
	
	public AliSmsUtil(String accessKeyId, String accessKeySecret) {
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
	}

	public AliSmsUtil(String accessKeyId, String accessKeySecret, String signName) {
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
		this.signName = signName;
	}

	private IAcsClient prepare() throws ClientException, com.aliyuncs.exceptions.ClientException {
		// 可自助调整超时时间
		System.setProperty("sun.net.client.defaultConnectTimeout", overTime);
		System.setProperty("sun.net.client.defaultReadTimeout", overTime);
		// 初始化acsClient,暂不支持region化
		IClientProfile profile = DefaultProfile.getProfile(area, accessKeyId, accessKeySecret);
		DefaultProfile.addEndpoint(area, area, product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);
		return acsClient;
	}


	/**
	 * 发送短信 (对同一个手机号码发送短信验证码，支持1条/分钟，5条/小时，10条/天。一个手机号码通过阿里云短信服务平台只能收到40条/天)
	 * 如果业务限流和非法手机号 抛出
	 * 
	 * @param phones
	 *            手机号码集合
	 * @return 发送成功生成的BIZ
	 */
	public String sendSms(String...phones) {
		if (StringUtil.isEmpty(this.accessKeyId)) {
			throw new RuntimeException("accessKeyId must not be null !");
		}

		if (StringUtil.isEmpty(this.accessKeySecret)) {
			throw new RuntimeException("accessKeySecret must not be null !");
		}

		if (StringUtil.isEmpty(this.signName)) {
			throw new RuntimeException("signName must not be null !");
		}

		if (phones.length == 0) {
			throw new RuntimeException("phones must not be null !");
		}

		try {
			// 准备工作
			IAcsClient acsClient = prepare();
			SendSmsRequest request = new SendSmsRequest();
			// 必填:待发送手机号
			StringBuffer sb = new StringBuffer();
			for (String p : phones) {
				sb.append(p + ",");
			}
			sb.deleteCharAt(sb.length() - 1);
			request.setPhoneNumbers(sb.toString());
			// 必填:短信签名-可在短信控制台中找到
			request.setSignName(signName);
			// 必填:短信模板-可在短信控制台中找到
			request.setTemplateCode(templateCode);
			// 转换参数为json
			if (!StringUtil.isEmpty(this.params) || this.params.get(0) == null) {
				request.setTemplateParam(JsonUtil.beanToJson(params));
			}
			// 选填-上行短信扩展码(无特殊需求用户请忽略此字段)
			// request.setSmsUpExtendCode("90997");
			// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
			// request.setOutId("yourOutId");
			// 此处可能会抛出异常
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if (!"OK".equals(sendSmsResponse.getCode())) {
				throw new RuntimeException(sendSmsResponse.getCode() + ":" + getCodeRemark(sendSmsResponse.getCode()));
			}
			return sendSmsResponse.getBizId();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public String getTemplateCode() {
		return templateCode;
	}

	public AliSmsUtil setTemplateCode(String templateCode) {
		this.templateCode = templateCode;
		return this;
	}

	public Map<String, String> getParams() {
		return params;
	}

	public AliSmsUtil setParams(Map<String, String> params) {
		if(params!=null){
			this.params = params;
		}
		return this;
	}
	
	public AliSmsUtil setParams(String key,String val) {
		this.params.put(key, val);
		return this;
	}

	public String getSignName() {
		return signName;
	}

	public AliSmsUtil setSignName(String signName) {
		this.signName = signName;
		return this;
	}
	
	public AliSmsUtil setArea(String area) {
		if(!StringUtil.isEmpty(area)){
			this.area = area;
		}
		return this;
	}

	public AliSmsUtil setOverTime(String overTime) {
		if(!StringUtil.isEmpty(overTime)){
			this.overTime = overTime;
		}
		return this;
	}

	private String getCodeRemark(String code){
		String result = "OK";
		switch (code){
            case "isp.RAM_PERMISSION_DENY":
                result = "RAM权限DENY";
                break;
            case "isv.OUT_OF_SERVICE":
                result = "业务停机";
                break;
            case "isv.PRODUCT_UN_SUBSCRIPT":
                result = "未开通云通信产品的阿里云客户";
                break;
            case "isv.PRODUCT_UNSUBSCRIBE":
                result = "产品未开通";
                break;
            case "isv.ACCOUNT_NOT_EXISTS":
                result = "账户不存在";
                break;
            case "isv.ACCOUNT_ABNORMAL":
                result = "账户异常        ";
                break;
            case "isv.SMS_TEMPLATE_ILLEGAL":
                result = "短信模板不合法";
                break;
            case "isv.SMS_SIGNATURE_ILLEGAL":
                result = "短信签名不合法";
                break;
            case "isv.INVALID_PARAMETERS":
                result = "参数异常";
                break;
            case "isv.MOBILE_NUMBER_ILLEGAL":
                result = "非法手机号";
                break;
            case "isv.MOBILE_COUNT_OVER_LIMIT":
                result = "手机号码数量超过限制";
                break;
            case "isv.TEMPLATE_MISSING_PARAMETERS":
                result = "模板缺少变量";
                break;
            case "isv.BUSINESS_LIMIT_CONTROL":
                result = "业务限流";
                break;
            case "isv.INVALID_JSON_PARAM":
                result = "JSON参数不合法，只接受字符串值";
                break;
            case "isv.PARAM_LENGTH_LIMIT":
                result = "参数超出长度限制";
                break;
            case "isv.PARAM_NOT_SUPPORT_URL":
                result = "不支持URL";
                break;
            case "isv.AMOUNT_NOT_ENOUGH":
                result = "账户余额不足";
                break;
            case "isv.TEMPLATE_PARAMS_ILLEGAL":
                result = "模板变量里包含非法关键字";
                break;
        }
		return result;
	}

	public static void main(String[] args) {
		AliSmsUtil util = new AliSmsUtil("LTAI4FgG53Li99h43cMVqDmT","u4VUWbBQKkbHUip72xs8VJiuznjr43");
		util.setSignName("易优采");
		util.setTemplateCode("SMS_202550795");
		Map<String,String> param = new HashMap<>();
		param.put("code","1234");
		util.setParams(param);
		util.sendSms("18606166467");

	}
	
}
